var express = require('express');
var router = express.Router();
var Users = require('./../models/users');
var UUID = require('uuid-random');
require('./../util/util');

// 登陆接口
router.post('/login', (req, res, next) => {
  let param = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  };
  Users.findOne(param, (err, userDoc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      if (userDoc) {
        res.cookie("userId", userDoc.userId, {
          path: '/', // cookie存放位置
          maxAge: 1000 * 60 * 60 // cookie存活时间
        });
        res.cookie("userName", userDoc.userName, {
          path: '/',
          maxAge: 1000 * 60 * 60
        });
        // req.session.user = userDoc;
        res.json ({
          status: '0',
          msg: 'success',
          result: userDoc.userName
        })
      } else {
        res.json({
          status: '1',
          msg: "用户名或密码不正确"
        })
      }
    }
  })
});

// 登出接口
router.post('/logout', (req, res, next) => {
  res.cookie("userId", "", {
    path: '/',
    maxAge: -1
  });
  res.cookie("userName", "", {
    path: '/',
    maxAge: -1
  });
  res.json({
    status: '0',
    msg: 'login out',
    result: 'success'
  })
});

// 登陆状态校验
router.get('/checkLogin', (req, res, next) => {
  if (req.cookies.userName) {
    res.json({
      status: '0',
      msg:'',
      result: req.cookies.userName
    })
  } else {
    res.json({
      status: '1',
      msg:'未登录',
      result: ''
    })
  }
});

// 查询购物车数据
router.get('/getCartList', (req, res, next) => {
  let userId = req.cookies.userId;
  Users.findOne({userId: userId}, (errUser, userDoc) => {
    if (errUser) {
      res.json({
        status: '1',
        msg: errUser.message,
        result: ''
      });
    } else {
      res.json({
        status: '0',
        msg: 'success',
        result: userDoc.cartList
      })
    }
  })
});

// 查询购物车商品数量，用于头部显示
router.get('/getCartCount', (req, res, next) => {
  let userId = req.cookies.userId;
  Users.findOne({userId: userId}, (errUser, userDoc) => {
    if (errUser) {
      res.json({
        status: '1',
        msg: errUser.message,
        result: ''
      });
    } else {
      let cartCount = 0;
      userDoc.cartList.forEach(item => {
        cartCount += parseInt(item.productNum)
      })
      res.json({
        status: '0',
        msg: 'success',
        result: cartCount
      })
    }
  })
});

// 购物车商品状态更新接口
router.post('/cart/goodsFresh', (req, res, next) => {
  let updateCartList = req.body.updateCartList;
  let userId = req.cookies.userId;
  Users.findOne({userId: userId}, (errUser, userDoc) => {
    if (errUser) {
      res.json({
        status: '1',
        msg: errUser.message,
        result: ''
      });
    } else {
      userDoc.cartList = updateCartList;
      userDoc.save((errSave, saveDoc) => {
        if (errSave) {
          res.json({
            status: '1',
            msg: errSave.message,
            result: ''
          })
        } else {
          res.json({
              status: '0',
              msg: '购物车状态更新成功',
              result: 'success'
          })
        }
      })
    }
  })
});

// 移除购物车
router.post('/cart/del', (req, res, next) => {
  let productId = req.body.productId;
  let userId = req.cookies.userId;
  Users.update({
    userId: userId
  },{$pull: {
      'cartList':{
        'productId': productId
      }
    }
  }, (errUserUpdate, userDoc) => {
    if (errUserUpdate) {
      res.json({
        status: '1',
        msg: errUserUpdate.message,
        result: ''
      });
    } else {
      res.json({
        status: '0',
        msg: '商品移除购物车成功',
        result: 'success'
      })
    }
  })
});

// 查询地址列表数据
router.get('/getAddressList', (req, res, next) => {
  let userId = req.cookies.userId;
  Users.findOne({userId: userId}, (errUser, userDoc) => {
    if (errUser) {
      res.json({
        status: '1',
        msg: errUser.message,
        result: ''
      });
    } else {
      res.json({
        status: '0',
        msg: 'success',
        result: userDoc.addressList
      })
    }
  })
});

// 设置默认地址
router.post('/setDefaultAddress', (req, res, next) => {
  let userId = req.cookies.userId,
      addressId = req.body.addressId;
  if (!addressId) {
    res.json({
      status: '1',
      msg: 'addressId is null',
      result: ''
    })
  } else {
    Users.findOne({
      userId: userId
    }, (errUser, userDoc) => {
      if (errUser) {
        res.json({
          status: '1',
          msg: errUser.message,
          result: ''
        })
      } else {
        userDoc.addressList.forEach(item => {
          if (item.addressId == addressId) {
            item.isDefault = true;
          } else {
            item.isDefault = false;
          }
        });
        userDoc.save((errSave, saveDoc) => {
          if (errSave) {
              res.json({
                  status: '1',
                  msg: errSave.message,
                  result: ''
              })
          } else {
              res.json({
                  status: '0',
                  msg: '默认地址设置成功',
                  result: 'success'
              })
          }
        })
      }
    })
  }
});

// 删除地址
router.post('/deleteAddr', (req, res, next) => {
  let userId = req.cookies.userId,
      addressId = req.body.addressId;
  Users.update({
    userId:userId
  },{$pull: {
      'addressList':{
        'addressId': addressId
      }
    }
  }, (errUserUpdate, userDoc) => {
    if (errUserUpdate) {
      res.json({
        status: '1',
        msg: errUserUpdate.message,
        result: ''
      })
    } else {
      res.json({
        status: '0',
        msg: '删除地址成功',
        result: 'success'
      })
    }
  })
})

// 新增地址
router.post('/addAddr', (req, res, next) => {
  let userId = req.cookies.userId,
      addrForm = req.body.addrForm;
  addrForm.addressId = UUID();
  console.log(addrForm);
  if (!(addrForm.userName && addrForm.streetName && addrForm.tel)) {
    res.json({
      status: '1',
      msg: '必填信息未填写',
      result: addrForm
    })
  } else {
    Users.findOne({userId: userId}, (errUser, userDoc) => {
      if (errUser) {
        res.json({
          status: '1',
          msg: errUser.message,
          result: ''
        })
      } else {
        if (addrForm.isDefault) {
          userDoc.addressList.forEach(item => {
            item.isDefault = false
          })
        }
        userDoc.addressList.push(addrForm);
        userDoc.save((errSave, saveDoc) => {
          if (errSave) {
            res.json({
              status: '1',
              msg: errSave.message,
              result: ''
            })
          } else {
            res.json({
              status: '0',
              msg: '地址添加成功',
              result: 'success'
            })
          }
        })
      }
    })
  }
})

// 创建订单
router.post('/createOrder', (req, res, next) => {
  let userId = req.cookies.userId,
      orderInfo = req.body.orderInfo;
  Users.findOne({
    userId: userId
  }, (errUser, userDoc) => {
    if (errUser) {
      res.json({
        status: '1',
        msg: errUser.message,
        result: ''
      })
    } else {
      let addressInfo = '', goodsList = [];
      userDoc.addressList.forEach(item => {
        if (item.addressId == orderInfo.addressId) {
          addressInfo = item;
        }
      });
      userDoc.cartList.filter(item => {
        if (item.checked) {
          goodsList.push(item);
        }
      });

      let platForm = '0021';
      let r1 = Math.floor(Math.random()*10);
      let r2 = Math.floor(Math.random()*10);

      let sysDate = new Date().Format('yyyyMMddhhmmss');
      let createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
      let orderId = platForm + r1 + sysDate + r2;
      let order = {
        orderId: orderId,
        orderTotal: orderInfo.orderPrice,
        addressInfo: addressInfo,
        goodsList: goodsList,
        orderStatus: '1',
        createDate: createDate,
      };

      userDoc.orderList.push(order);
      userDoc.save((errSave, saveDoc) => {
        if (errSave) {
          res.json({
            status: '1',
            msg: errSave.message,
            result: ''
          })
        } else {
          res.json({
            status: '0',
            msg: '订单提交成功',
            result: order
          })
        }
      })
    }
  })
})

// 订单查询
router.get('/getOrderInfo', (req, res, next) => {
  let userId = req.cookies.userId,
      orderId = req.body.orderId;
  Users.findOne({
    userId: userId
  }, (errUser, userDoc) => {
    if (errUser) {
      res.json({
        status: '1',
        msg: errUser.message,
        result: '',
      })
    } else {
      let orderInfo = [];
      userDoc.orderList.filter(item => {
        if (item.orderId == orderId) {
          orderInfo = item;
        }
      })
      if (orderInfo.length > 0) {
        res.json({
          status: '0',
          msg: '',
          result: orderInfo
        })
      } else {
        res.json({
          status: '1',
          msg: '找不到订单信息',
          result: ''
        })
      }
    }
  })
})

module.exports = router;
